/*
 * @Author: eycode
 * @Date: 2021-05-21 11:05:25
 * @LastEditTime: 2021-05-21 11:21:05
 * @LastEditors: eycode
 * @Description: 摇杆父节点
 * @Other: 
 */

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {
    /**摇杆节点 */
    @property(cc.Node)
    Rocker: cc.Node = null;

    /**摇杆的移动的最大范围 */
    private _max_r: number = 100;

    /**默认向量 */
    public dir: cc.Vec2 = cc.v2(0, 0);

    start() {
        this.Rocker.x = 0;
        this.Rocker.y = 0;
        this.dir = cc.v2(0, 0);

        this.Rocker.on(cc.Node.EventType.TOUCH_START, this._touchStart, this);
        this.Rocker.on(cc.Node.EventType.TOUCH_MOVE, this._touchMove, this);
        this.Rocker.on(cc.Node.EventType.TOUCH_END, this._touchEnd, this);
        this.Rocker.on(cc.Node.EventType.TOUCH_CANCEL, this._touchEnd, this);
    }

    private _touchStart(event) {
        var w_pos = event.getLocation();
        var pos = this.node.convertToNodeSpaceAR(w_pos);
        var len = pos.mag();
        this.dir.x = pos.x / len;
        this.dir.y = pos.y / len;
        if (len > this._max_r) {
            pos.x = this._max_r * pos.x / len;
            pos.y = this._max_r * pos.y / len;
        }
        this.Rocker.setPosition(pos);
    }

    private _touchMove(event) {
        var w_pos = event.getLocation();
        var pos = this.node.convertToNodeSpaceAR(w_pos);
        var len = pos.mag();
        this.dir.x = pos.x / len;
        this.dir.y = pos.y / len;
        if (len > this._max_r) {
            pos.x = this._max_r * pos.x / len;
            pos.y = this._max_r * pos.y / len;
        }
        this.Rocker.setPosition(pos);
    }

    private _touchEnd() {
        this.Rocker.setPosition(cc.v2(0, 0));
        this.dir = cc.v2(0, 0);
    }
}
